using System;
using System.Threading;
using System.IO;

using Microsoft.SPOT;

using mfRCF.Core;
using mfRCF.Core.Extensions;

using mfXmlSerializer;

using mfLogger;

using OST.Shared.SharedTypes;
using OST.Persistence;
using OST.Shared;

namespace OST.Commands
{
    using Extensions;

    /// <summary>
    /// sets the content of the 'index.htm' file in removable-storage
    /// </summary>
    public class WebClientPOSTCommand : mfRcfCommand
    {
        #region Consts
        private const string C_STR_INDEX_FILE_NAME = "index.htm";
        #endregion

        #region CTOR

        public WebClientPOSTCommand(string httpPath)
            : base(httpPath, new mfPOSTMethod())
        {
        }

        #endregion

        #region Properties

        /// <summary>
        /// wrapper-property 4 logging
        /// </summary>
        private ILoggerAppender Logger
        {
            get
            {
                return mfLogger.mfLogger.Instance;
            }
        }

        #endregion

        #region mfRcfCommand
        public override void ExecuteCommand(mfIHttpContext httpContext)
        {
            try
            {
                if (!RemoveableMediaStorageProvider.Instance.IsStorageConntected)
                    throw new OSTException("no storage loaded");

                var storage = RemoveableMediaStorageProvider.Instance.RootDirectory;

                var indexFilePath = Path.Combine(storage, C_STR_INDEX_FILE_NAME);

                var indexFileStream = new StreamWriter(indexFilePath, false);

                //read to the end of the HttpListenerRequest.InputStream
                var inputLength = 0;
                do
                {
                    var inputBytes = httpContext.Request.InputStream.ReadAllBytes();
                    inputLength = inputBytes.Length;
                    indexFileStream.BaseStream.Write(inputBytes, 0, inputBytes.Length);
                    inputBytes = null;
                }
                while (httpContext.Request.InputStream.Length != inputLength);

                indexFileStream.Close();
                indexFileStream.Dispose();

                this.WriteHttpResponseOK(httpContext, C_STR_INDEX_FILE_NAME + " updated");

                Logger.Info(GetType() + " executed, " + Debug.GC(true) + " bytes free");
            }
            catch (Exception ex)
            {
                this.WriteHttpResponseError(httpContext, ex);
            }
        }
        #endregion
    }
}
